import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import sqlite3
import os

class ImagePage(ttk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller
        
        # 创建导航栏
        self.nav_frame = ttk.Frame(self)
        self.nav_frame.pack(fill='x', padx=5, pady=5)
        
        # 刷新按钮
        self.refresh_btn = ttk.Button(self.nav_frame, text='刷新数据', command=self.update_data)
        self.refresh_btn.pack(side='left')
        
        # 创建画布和滚动条
        self.canvas = tk.Canvas(self)
        self.scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.scrollable_frame = ttk.Frame(self.canvas)
        
        # 配置画布
        self.canvas.configure(yscrollcommand=self.scrollbar.set)
        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        
        # 布局组件
        self.scrollbar.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)
        
        # 绑定滚动事件
        self.scrollable_frame.bind("<Configure>", 
            lambda e: self.canvas.configure(
                scrollregion=self.canvas.bbox("all")
            )
        )
        
    def update_data(self):
        # 清除旧内容
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        
        # 从数据库获取最近15张图片
        conn = sqlite3.connect('sensor_data.db')
        c = conn.cursor()
        c.execute("SELECT image_path FROM image_metadata ORDER BY timestamp DESC LIMIT 15")
        images = c.fetchall()
        conn.close()
        
        # 显示缩略图
        row, col = 0, 0
        for idx, (img_path,) in enumerate(images):
            if os.path.exists(img_path):
                img = Image.open(img_path)
                img.thumbnail((200, 200))
                photo = ImageTk.PhotoImage(img)
                
                frame = ttk.Frame(self.scrollable_frame)
                frame.grid(row=row, column=col, padx=5, pady=5)
                
                label = ttk.Label(frame, image=photo)
                label.image = photo  # 保持引用
                label.pack()
                
                ttk.Label(frame, text=f"图片{idx+1}").pack()
                
                col += 1
                if col > 2:  # 每行显示3列
                    col = 0
                    row += 1